package com.hyz.reggie.controller;

import com.hyz.reggie.pojo.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/common")
@RestController
public class UploadCl {
    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R uploadImg(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        filename = filename.substring(filename.indexOf("."));
        String name = UUID.randomUUID().toString().replace("-", "");
        filename = name + filename;
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        file.transferTo(new File(path + filename));
        return R.success(filename);
    }

    @GetMapping("/download")
    public void downloadImg(String name, HttpServletResponse response) throws Exception {
        FileInputStream fis = new FileInputStream(path+name);
        response.setContentType("image/jpeg");
        ServletOutputStream os = response.getOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fis.read(bytes)) != -1){
           os.write(bytes,0,len);
           os.flush();
        }
        os.close();
        fis.close();
    }

}
